package com.ty.common.log.logbackAdvice;

import ch.qos.logback.classic.spi.LoggingEvent;
import com.ty.common.log.utils.DesensitizationUtil;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;

/**
 * 脱敏类
 * @Author: TangYuan
 * @Date: 2025/8/19 15:56
 */
@Slf4j
public class DesensitizationAppender {

    private static final String MESSAGE = "message";

    private static final String FORMATTED_MESSAGE = "formattedMessage";

    public void operation(LoggingEvent event) {
        if (event.getArgumentArray() != null) {
            String eventFormattedMessage = event.getFormattedMessage();
            DesensitizationUtil util = new DesensitizationUtil();
            String changeMessage = util.customChange(eventFormattedMessage);
            if (!(null == changeMessage || changeMessage.isEmpty())) {
                try {
                    Class<? extends LoggingEvent> eventClass = event.getClass();
                    Field message = eventClass.getDeclaredField(MESSAGE);
                    message.setAccessible(true);
                    message.set(event, changeMessage);
                    Field formattedMessage = eventClass.getDeclaredField(FORMATTED_MESSAGE);
                    formattedMessage.setAccessible(true);
                    formattedMessage.set(event, changeMessage);
                } catch (IllegalAccessException | NoSuchFieldException e) {
                    log.error("DesensitizationAppender err", e);
                }
            }
        }
    }
}
